<template>
	<el-cascader
		ref="cascaderAreaRef"
		placeholder="请选择适用地区"
		clearable
		:collapse-tags="true"
		:show-all-levels="false"
		:options="options"
		:props="props"
		:disabled="disabled"
		:value="cascaderValue"
		@change="change"
	/>
</template>

<script>
	import ucApi from "@rc/apis/uc/index.mjs";

	export default {
		props: {
			/**
			 * 当前的默认的选中值
			 * 1.支持v-model
			 * 2.默认单选，支持传入两种风格  1.[子areaCode] 2.[父areaCode,子areaCode]，注：修改后传出的是第二种格式
			 * 3.多选(propsOptions.multiple = true)  1. [子areaCode,子areaCode,...]  2. [[父areaCode,子areaCode], [父areaCode,子areaCode]...]，注：修改后传出的是第二种格式
			 */
			value: {
				type: Array,
				default: () => []
			},
			params: {
				type: Object,
				default: () => {
					return {
						areaCode: ""
					};
				}
			},
			// 是否显示全国
			hasAllArea: {
				type: Boolean,
				default: false
			},
			// cascader组件的props参数，会与组件配置的进行合并 https://element.eleme.cn/#/zh-CN/component/cascader
			propsOptions: {
				type: Object,
				default: () => {}
			},
            disabled:{//是否禁用
                type: Boolean,
				default: false
            }
		},
		data() {
			return {
				props: {
					// 级联框基础配置
					value: "areaCode",
					label: "areaName"
				},
				paramsObj: {},
				options: [], // 树状列表
				flatOptions: [], // 扁平化的列表
                changeValue:null//存储当前选择的值,供api_getChapterList使用 因为value或cascaderValue无法立即得到改变的最新数据
			};
		},
		computed: {
			cascaderValue() {
				//经过处理的，符合cascader组件格式需求标准的value
				let result = [];
				// 这种是父级子级全有的单选[父id,子id]
				if (this.props.multiple) {
					// 多选类型
					result = this.value.map((i) => {
						if (Array.isArray(i)) {
							// 父级子级全有的多选[[],[]]
							return i;
						} else {
							// 只有子级的多选[子id1,子id2]
							const findItem = this.flatOptions.find((i2) => i2.areaCode === i);
							return findItem ? findItem.ids : [];
						}
					});
					result = result.filter((i) => i); // 过滤掉为null的未匹配上的id
				} else {
					// 单选类型
					const childrenId = this.value[this.value.length - 1];
					const findItem = this.flatOptions.find((i) => i.areaCode === childrenId);
					result = findItem ? findItem.ids : [];
				}
				return result;
			}
		},
		methods: {
			change(data) {
				if (this.props.multiple && data.some((i) => i[i.length - 1] === "0000")) {
					// 如果是多选，并且选中的有“全国”选项
					if (this.value.some((i) => i === "0000" || i[i.length - 1] === "0000")) {
						// 之前就选了全国，说明是选了其他地区，把全国取消勾选
						data = data.filter((i) => i[i.length - 1] !== "0000");
					} else {
						// 之前没选全国，说明是选了全国，把其他地区取消勾选
						data = ["0000"];
					}
				}
                this.changeValue = data;
				this.$emit("input", data);
				this.$emit("change", data);
			},
			api_getCheckedNodes() {
				return this.$refs.cascaderAreaRef.getCheckedNodes();
			},
            api_clearCheckedNodes(){
                // 清空选中的节点
                this.$refs.cascaderAreaRef.$refs.panel.clearCheckedNodes();
                // 设置为空可以让节点不高亮显示
                this.$refs.cascaderAreaRef.$refs.panel.activePath = [];
                this.changeValue = [];
            },
            //获取选中的地区列表
            api_getAreaList(){
                let areaIds =  this.changeValue?this.changeValue:this.cascaderValue;
                let areaList = [];
                if (!this.props.multiple && areaIds.length) {
                    areaIds =  [areaIds];
                } else {
                    areaIds = areaIds.map(i => {
                        if (Array.isArray(i)) {
                            return i;
                        } else {
                            return [i];
                        }
                    });
                }
				areaIds.forEach((areaId) => {
                        const optionArea =  this.options.find(optionItem=>optionItem.areaCode === areaId[0]);
                        let children = null;
                        if(optionArea.children && areaId.length===2){
                           children = optionArea.children.find(optionItem=>optionItem.areaCode === areaId[1]);
                        }
                        let areaObj = {};
                        if (!children || children.length === 0) {
                            areaObj.cityId = optionArea.areaCode;
                            areaObj.cityName = optionArea.areaName;
                            areaObj.provinceId = optionArea.areaCode;
                            areaObj.provinceName = optionArea.areaName;
                        }
                        if(children){
                            areaObj.provinceId = optionArea.areaCode;
                            areaObj.provinceName = optionArea.areaName;
                            areaObj.cityId = children.areaCode;
                            areaObj.cityName = children.areaName;
                        }
                        areaList.push(areaObj);
				});
                return areaList;
            }
		},
		created() {
			// 合并配置
			this.props = { ...this.props, ...this.propsOptions };
			//查询参数
			this.paramsObj = { ...this.paramsObj, ...this.params };
			// 初始化内容数据
			ucApi.queryAreaList({
				data: {
					...this.paramsObj
				},
				success: ({ data }) => {
					if (this.hasAllArea) {
						data.unshift({ areaCode: "0000", areaName: "全国", existNode: "true" });
					}
					this.options = data;
					// 扁平化的递归函数
					const flatFun = (arr, item, ids) => {
						arr.push({
							areaCode: item.areaCode,
							areaName: item.areaName,
							ids: [...ids, item.areaCode] // 父子id集合
						});
						if (item.children && item.children.length) {
							item.children.forEach((item2) => {
								flatFun(arr, item2, [...ids, item.areaCode]);
							});
						}
					};
					this.options.forEach((item2) => {
						flatFun(this.flatOptions, item2, []);
					});

					const treeList = JSON.parse(JSON.stringify(data));
					const flatList = JSON.parse(JSON.stringify(this.flatOptions));

					this.$emit("ready", treeList, flatList);
				}
			});
		}
	};
</script>

<style scoped lang="less">
	/deep/ .el-cascader__tags .el-tag {
		height: 23px;
        line-height: 23px;

        .el-icon-close {
            top: 1px;
        }
	}
</style>
